
#include "AppWin.hpp"
#include <QtGui/QKeyEvent>
#include <iostream>
using namespace std;
#include <Module-EMap/EMapAccess.hpp>

/* 一共有6个常数 */
const float
longitude_s = 108.9084,
  latitude_s = 34.2298,
  longtitude_len = 0.01012,
  latitude_len = 0.0082;

const int max_zoom_factor = 3;
const char *MIF_FILE_NAME = "m.mif";

float  current_x = 108.9140, current_y = 34.2334;
bool   is_moved = true;
int    zoom_factor=0;

int    img_idx[4][2];
float  pos_x, pos_y;		// 标号为2的img窗口相对位置

AppWin::AppWin( void )
{
  window.setupUi( this );
  QObject::connect( window.Zin, SIGNAL(clicked()), this, SLOT(on_zin_click()) );
  QObject::connect( window.Zout, SIGNAL(clicked()), this, SLOT(on_zout_click()) );
  connect( this, SIGNAL(reload()), this, SLOT(on_reload()) );

  ModuleEMapData::set_map_range( longitude_s,latitude_s,longtitude_len,latitude_len );
  ModuleEMapData::init( MIF_FILE_NAME, window.widget->width(), window.widget->height(), max_zoom_factor);

  reload( );
}


void AppWin::on_zin_click()
{
  if( zoom_factor < max_zoom_factor )
    zoom_factor++;

  reload();
}

void AppWin::on_zout_click()
{
  if( zoom_factor > 0 )
    zoom_factor--;

  reload();
}

void AppWin::post_reload( void )
{
  emit reload();
}

void AppWin::on_reload( void )
{
  //  cout << current_x << '\t' << current_y << endl;
  // 经纬度转化
  float PX, PY;
  PX = (current_x-longitude_s)/longtitude_len;
  PY = (current_y-latitude_s)/latitude_len;

  // 格子位置
  int count = 1 << zoom_factor;
  int A = PX*( count<<1 );
  int B = PY*( count<<1 );

  // 格子位置
  int val;
  val = (A-1)>>1;
  img_idx[2][0] = val;
  img_idx[0][0] = (val >= 0 && val < count)? val:-1;
  val = (A+1)>>1;
  img_idx[1][0] = img_idx[3][0] = (val >= 0 && val < count)? val:-1;
  val = (B-1)>>1;
  img_idx[0][1] = img_idx[1][1] = (val >= 0 && val < count)? val:-1;
  val = (B+1)>>1;
  img_idx[2][1] = val;
  img_idx[3][1] = (val >= 0 && val < count)? val:-1;

  // pos_x, pos_y
  float LX,LY;
  LX = PX*(float)count - 0.5;
  LY = PY*(float)count - 0.5;

  pos_x = (float)img_idx[2][0] - LX;
  pos_y = -((float)img_idx[2][1] - LY);

  img_idx[2][0] = img_idx[0][0];
  img_idx[2][1] = img_idx[3][1];

  QString  str = QString("pos:%1 %2").arg( current_x ).arg( current_y );
  window.statusBar->showMessage( str );
  window.widget->repaint();

  is_moved = false;
}

AppWin::~AppWin()
{
  ModuleEMapData::clear();
}

void AppWin::keyPressEvent( QKeyEvent * event )
{
  switch( event->key() )
    {
    case Qt::Key_W:
      current_y += 0.0001;
      is_moved = true;
      break;
    case Qt::Key_S:
      current_y -= 0.0001;
      is_moved = true;
      break;
    case Qt::Key_A:
      current_x -= 0.0001;
      is_moved = true;
      break;
    case Qt::Key_D:
      current_x += 0.0001;
      is_moved = true;
      break;
    default:
      ;
      }

  if( is_moved )
    reload();
}
